package com.jian.ecommercial.config;

import com.jian.ecommercial.intercept.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class LoginInterceptorConfigure implements WebMvcConfigurer {

    @Override
    //配置拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        //1.创建自定义的拦截器对象
        HandlerInterceptor interceptor =  new LoginInterceptor();
        //2.配置白名单并存放在一个List集合
        List<String> patterns = new ArrayList<>();
        patterns.add("/bootstrap3/**");
        patterns.add("/css/**");
        patterns.add("/images/**");
        patterns.add("/js/**");
        patterns.add("/web/register.html");
        patterns.add("/web/login.html");
        patterns.add("/web/index.html");
        patterns.add("/web/product.html");
        patterns.add("/stockuser/reg");
        patterns.add("/stockuser/login");
        patterns.add("/districts/**");
        patterns.add("/favicon.ico");
        patterns.add("/cart.json");
        patterns.add("/error");
        patterns.add("/stocks/list");

        //registry.addInterceptor(interceptor);完成拦截
        // 器的注册,后面的addPathPatterns表示拦截哪些url
        //这里的参数/**表示所有请求,再后面的excludePathPatterns表
        // 示有哪些是白名单,且参数是列表
        registry.addInterceptor(interceptor)
                .addPathPatterns("/**")
                .excludePathPatterns(patterns);
    }

    //@Override
    //public void addCorsMappings(CorsRegistry corsRegistry){
    //    /**
    //     * 所有请求都允许跨域，使用这种配置就不需要
    //     * 在interceptor中配置header了
    //     */
    //    corsRegistry.addMapping("/**")
    //            .allowCredentials(true)
    //            .allowedOrigins("http://localhost:8999")
    //            .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
    //            .allowedHeaders("*")
    //            .maxAge(3600);
    //}
}
